package com.ijuit.common;

import java.io.File;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ijuit.model.user.User;
import com.ijuit.web.IndexAction;
import com.ijuit.web.user.UserAction;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.spring.SpringPlugin;

public class IJuitConfig extends JFinalConfig{
   private ApplicationContext ctx;
     
    // 原因是 jfinal 先实例化 JFinalConfig 在 JFinal.init 初始化相关配置 
    public ApplicationContext getApplicationContext(){
        if(ctx == null) ctx = WebApplicationContextUtils.getWebApplicationContext(JFinal.me().getServletContext());
        return ctx;
    }
	/**
	 * 配置常量
	 */
	@Override
	public void configConstant(Constants me) {
		//加载数据库配置
		loadPropertyFile(new File(PathKit.getWebRootPath()+"/WEB-INF/configs/config.properties"));//加载数据库配置
		//设置当前模式为开发模式
		me.setDevMode(getPropertyToBoolean("devMode", false));
		//设视图类型
		//me.setViewType(ViewType.JSP);
		me.setError404View("common/404.html");//配置404页面
		me.setError404View("common/503.html");//配置503页面
	}
	/**
	 * 配置路由
	 */
	@Override
	public void configRoute(Routes me) {
		me.add("/", IndexAction.class);//配置默认进入页面
		me.add("/user", UserAction.class);//配置默认进入页面
	}

	/**
	 * 配置插件
	 */
	@Override
	public void configPlugin(Plugins me) {
		
		//添加spring插件
		me.add(new SpringPlugin(getApplicationContext()));
		
		// 配置C3p0数据库连接池插件
		C3p0Plugin c3p0Plugin = new C3p0Plugin(getProperty("jdbcUrl"), getProperty("user"), getProperty("password").trim());
		me.add(c3p0Plugin);
		
		// 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
		me.add(arp);
		
		
		arp.addMapping("user", User.class);	// 映射user 表到 User模型
	}

	/**
	 * 配置拦截器
	 */
	@Override
	public void configInterceptor(Interceptors me) {
		
	}

	@Override
	public void configHandler(Handlers me) {
		 //me.add(new ContextPathHandler());
	}

	public static void main(String[] args) {
		JFinal.start("WebRoot", 80, "/", 5);
	}
}
